package com.boomsecret.lock;

import org.apache.commons.lang3.RandomUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

/**
 * Created by wangjinliang on 2018/8/8.
 */
public class RWCollectionDemo {
    public static void main(String[] args) throws Exception {
        RWCollection rwCollection = new RWCollection();
        new Thread(() -> {
            while (true) {
                try {
                    System.out.println("obtain value -> " + rwCollection.getValue("testKey"));
                    Thread.sleep(700);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Thread.sleep(2000);
        new Thread(() -> {
            while (true) {
                try {
                    int testValue = RandomUtils.nextInt();
                    rwCollection.put("testKey", "value" + testValue);
                    System.out.println("update value -> " + testValue);
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    static class RWCollection {
        private Map<String, String> dataMap = new HashMap<>();
        private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

        public String getValue(String key) {
            ReadLock readLock = readWriteLock.readLock();
            readLock.lock();
            String value = dataMap.get(key);
            readLock.unlock();
            return value;
        }

        public void put(String key, String value) {
            WriteLock writeLock = readWriteLock.writeLock();
            writeLock.lock();
            dataMap.put(key, value);
            writeLock.unlock();
        }
    }
}